package com.lagou.filter;

import com.lagou.feign.UserFeignClient;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpCookie;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.RequestPath;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.ArrayList;
import java.util.List;

@Slf4j
@Component
public class TokenFilter implements GlobalFilter, Ordered {
    private static final List<String> PATH_LIST = new ArrayList<>();

    static {
        PATH_LIST.add("/api/user/register/");
        PATH_LIST.add("/api/user/isRegistered/");
        PATH_LIST.add("/api/user/login/");
        PATH_LIST.add("/api/code/create/");
    }

    @Autowired
    private UserFeignClient userFeignClient;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        String path = request.getPath().toString();
        for (String allowPath : PATH_LIST) {
            if (path.startsWith(allowPath)) {
                //如果请求路径在允许的路径中时直接放行
                return chain.filter(exchange);
            }
        }
        ServerHttpResponse response = exchange.getResponse();
        HttpCookie tokenCookie = request.getCookies().getFirst("token");
        if (tokenCookie == null) {
            // token不合法，拒绝访问
            response.setStatusCode(HttpStatus.UNAUTHORIZED); // 状态码
            String data = "Request be denied!";
            DataBuffer wrap = response.bufferFactory().wrap(data.getBytes());
            return response.writeWith(Mono.just(wrap));
        }
        String token = tokenCookie.getValue();
        String email = userFeignClient.info(token);
        log.info("token值为：" + token);
        log.info("根据token查找email结果：" + email);
        if (StringUtils.isEmpty(email)) {
            // token不合法，拒绝访问
            response.setStatusCode(HttpStatus.UNAUTHORIZED); // 状态码
            String data = "Request be denied!";
            DataBuffer wrap = response.bufferFactory().wrap(data.getBytes());
            return response.writeWith(Mono.just(wrap));
        }
        // 合法请求，放行，执行后续的过滤器
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }
}

